import React, { Component } from 'react';
import { Dimensions, Image } from 'react-native';
import RootSiblings from 'react-native-root-siblings';
import LoadingView, { LoadingProps } from './Loading';
import Confirm, { ConfirmProps as ConfirmConfig } from './Confirm';
import Toast, { ToastOptions } from './Toast';

let tipOffset = 60;
const init = () => {
  tipOffset = Math.round(Dimensions.get('window').height / 5);
  const _windowChanged = ({ window }) => {
    tipOffset = Math.round(window.height / 5);
  };
  Dimensions.addEventListener('change', _windowChanged);
};
init();

export const showLoading = (config?: LoadingProps) => {
  return showPopup(LoadingView, { ...config, loading: true });
};

export const hideLoading = () => {
  siblings[LoadingView.displayName]?.destroy?.();
  instances[LoadingView.displayName] = null;
  siblings[LoadingView.displayName] = null;
};

export const confirm = (config: ConfirmConfig) => {
  return showPopup(Confirm, config);
};

export const tip = (message, options: ToastOptions = {}) => {
  return Toast.show(message, {
    duration: Toast.durations.SHORT, // Toast.durations.LONG: 3500, Toast.durations.SHORT: 2000
    position: 0 - tipOffset, //<0表示离bottom的距离，>0表示离top的距离，0表示center
    shadow: true,
    animation: true,
    hideOnPress: true,
    delay: 0,
    ...options
  });
};

export const tipCenter = (message, options = {}) => {
  return tip(message, { ...options, position: Toast.positions.CENTER });
};

export const tipTop = (message, options = {}) => {
  return tip(message, { ...options, position: tipOffset });
};

export const tipSuccess = (message, options = {}) => {
  const childComponent = (
    <Image
      style={{ width: 32, height: 32, marginBottom: 10 }}
      source={require('./assets/success.png')}
      resizeMode="contain"
    />
  );
  return tip(message, {
    ...options,
    position: Toast.positions.CENTER,
    containerStyle: {
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      minWidth: 120
    },
    childComponent
  });
};

export default {
  showLoading,
  hideLoading,
  confirm,
  tip,
  tipCenter,
  tipTop,
  tipSuccess
};

// 所有图层实例
const siblings: any = {};
// 所有组件实例
const instances: any = {};

function getSiblings() {
  return siblings;
}

const showPopup = (Component, config = {}) => {
  const name = Component.displayName;
  const c = (
    <Component
      ref={o => {
        instances[name] = o;
      }}
      {...config}
      destroy={() => {
        siblings[name]?.destroy?.();
        instances[name] = null;
        siblings[name] = null;
      }}
    />
  );
  if (siblings[name]) {
    siblings[name]?.destroy?.();
    instances[name] = null;
    siblings[name] = null;
  }
  const sibling = new RootSiblings(c);
  siblings[name] = sibling;
  return () => {
    instances[name]?.hide();
  };
};
